package com.lagou.edu.processor;

import com.lagou.edu.pojo.*;
import com.lagou.edu.servlet.HttpServlet;
import com.lagou.edu.servlet.Servlet;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: RequestProcessor
 * @Auther: Jerry
 * @Date: 2020/8/1 0:08
 * @Desctiption: TODO
 * @Version: 1.0
 */
public class RequestProcessor extends Thread{

    private Socket socket;

    private Host host;

    public RequestProcessor(Socket socket, Host host) {
        this.socket = socket;
        this.host = host;
    }

    @Override
    public void run() {
        try {
            // 构建Request信息
            Request request = new Request(socket.getInputStream());

            // 构建Response信息
            Response response = new Response(socket.getOutputStream());

            service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void service(Request request, Response response) throws Exception {
        Servlet executeServlet = null;
        List<Context> contextList = host.getContextList();
        for (int i = 0; i < contextList.size(); i++) {
            Context context = contextList.get(i);
            // 处理请求uri：/demo1/lagou，因为demo1是contextName，因此需要去掉，用后面的/lagou去匹配servlet
            String[] split = request.getUri().split("/");
            // contextName不匹配则跳过
            if (!context.getContextName().equals(split[1])) {
                continue;
            }
            Map<String, Wrapper> wrapperMap = context.getWrapperMap();
            // 获取contextName之后的路径
            String uri = request.getUri();
            uri = uri.substring(uri.lastIndexOf("/"), uri.length());
            // 根据请求uri从wrapper中获取对应servlet
            Servlet servlet = wrapperMap.get(uri).getServlet();
            if (servlet!=null){
                executeServlet = servlet;
            }
        }

        if (executeServlet == null) {
            response.outputHtml(request.getUri());
        } else {
            HttpServlet httpServlet = (HttpServlet) executeServlet;
            httpServlet.service(request, response);
        }
        socket.close();
    }
}
